﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OfficeOpenXml.Drawing.Slicer.Style;
using org.apache.zookeeper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static Coldairarrow.Entity.Interface.YDOrdersDTO;

namespace Coldairarrow.Business.Interface
{
    public class YD_YDGetReportInterfaceBusiness : YDInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption YD_Query { get; set; }
        //报告ID
        public string ReportID { get; set; }
        //API密匙
        public string ApiKey { get; set; }
        public YD_YDGetReportInterfaceBusiness()
        {
            this.InterfaceName = "YD获取报告";
            //索引字段
            this.MapFields = GetMapField("YD_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            YD_Query = this.interfaceOption.Where(x => x.OperateType == "YD_Query").First();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="LX_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, YD_NoQueryEventArgs LX_NoQueryEventArgs)
        {
            //API请求是否成功
            LX_NoQueryEventArgs.Success = LX_NoQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, YD_QueryEventArgs queryEventArgs)
        {
            try
            {
               
                queryEventArgs.HttpClient.ContentType = "GET";
                //设置请求头参数
                //this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                //var auth = this.SqlDb.GetListBySql<Base_ConfigParameter>(@$"SELECT * FROM  Base_ConfigParameter(NOLOCK) WHERE Code='Yandex'");
                //Dictionary<string, string> headers = new Dictionary<string, string>();
                //headers.Add("Api-Key", auth.First().Value);
                //queryEventArgs.UrlQuery.Header = new Header() { Headers = headers };
                //queryEventArgs.Page.PageSize = YD_Query.ExcInterval;
                queryEventArgs.CustomData = queryEventArgs.HttpClient.Url;
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, YD_QueryEventArgs queryEventArgs)
        {
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("Api-Key", ApiKey);
            queryEventArgs.UrlQuery.Header = new Header() { Headers = headers };
            queryEventArgs.Page.PageSize = YD_Query.ExcInterval;
            queryEventArgs.HttpClient.Url = queryEventArgs.CustomData + this.ReportID;
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, YD_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
               
                YDReportDTO result = (YDReportDTO)JsonConvert.DeserializeObject<YDReportDTO>(queryEventArgs.ResultStr);
                if (!result.IsNullOrEmpty() && result.status == "OK" && result.result.status == "DONE")
                {
                    queryEventArgs.Page.Complete = true;
                    queryEventArgs.Rows = new List<string>() { result.result.file };
                }
                else
                { 
                Thread.Sleep(2000);
                
                }
                queryEventArgs.Success = true;
               
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            //获取报表代码
            List<string> code = await this.QueryAsync<string>(this.YD_Query, SqlDb);

        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
